package com.psg.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.psg.dao.CarDao;
import com.psg.dao.OrderDao;
import com.psg.pojo.Car;
import com.psg.pojo.Order;
import com.psg.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;
    @Resource
    private CarDao carDao;

    @Override
    public List<Order> selectOrder(Integer order_id) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id",order_id);
        wrapper.orderByDesc("id");
        List<Order> orders = orderDao.selectList(wrapper);
        return orders;
    }

    @Override
    public void insertOrder(Order order) { orderDao.insert(order); }

    @Override
    public void generateOrderByCarIds(int[] ids,int userId) {
        List<Car> carList = carDao.queryByIds(ids);
        JSONArray jsonArray = new JSONArray();
        Order order = new Order();
        AtomicReference<Double> totalPrice = new AtomicReference<>(0d);
        AtomicReference<Integer> totalNum = new AtomicReference<>(0);
        carList.forEach(car -> {
            totalPrice.updateAndGet(v -> v + car.getPrice() * car.getAccount());
            totalNum.getAndSet(totalNum.get() + 1);
            jsonArray.add(car.toOrderJson());
        });

        order.setNum(totalNum.get());
        order.setOstatus("已支付");
        order.setPrice(totalPrice.get());
        order.setPname(jsonArray.toJSONString());
        order.setOrder_id(userId);
        orderDao.insert(order);
        carDao.batchDeleteByIds(ids);
    }
}
